import java.io.IOException;
import java.net.*;

/**
 * UDP 搜索者，用于搜索服务方
 */
public class UDPSearcher {
    public static void main(String[] args) throws IOException {
        System.out.println("UDPProvider Started.");

        // 作为搜索方，无须指定一个端口，系统直接分配
        DatagramSocket datagramSocket = new DatagramSocket();

        /**
         * 构建一份request数据
         */
        String requestData = "Helloworld";
        byte[] requestDataBytes = requestData.getBytes(); // 未设定字符集
        // 直接根据发送者构建一个回送报文
        DatagramPacket requestPacket =  new DatagramPacket(requestDataBytes,
                requestDataBytes.length);
        requestPacket.setAddress(InetAddress.getLocalHost()); // 本机IP地址
        requestPacket.setPort(20000); // 端口是20000

        datagramSocket.send(requestPacket); // 发送



        /**
         * 接收UDP Provider回送的数据
         */
        // 构建接收实体
        final byte[] buf = new byte[512];
        DatagramPacket receivePack = new DatagramPacket(buf, buf.length);
        datagramSocket.receive(receivePack); // 接收

        // 打印接收到的信息与发送者的信息
        // 发送者的IP地址
        String ip = receivePack.getAddress().getHostAddress();
        // 发送者的端口
        int port = receivePack.getPort();
        // 数据大小
        int dataLen = receivePack.getLength();

        String data = new String(receivePack.getData(), 0, dataLen); // 假设报文内容都是String
        System.out.println("UDPSearcher receive from ip:" + ip + "\tport:" + port + "\tdata:" + data);


        /**
         * 完成
          */
        System.out.println("UDPSearcher Finished");
        datagramSocket.close();
    }
}
